import React, { useState, useMemo } from 'react';
import {
  Search,
  Calendar,
  Download,
  Trash2,
  Clock,
  File,
  CheckCircle,
  XCircle,
} from 'lucide-react';
import { ProcessTask, TaskType } from '@/types/video';

interface ProcessHistoryProps {
  tasks: ProcessTask[];
  onClearHistory?: () => void;
  onExportHistory?: () => void;
  className?: string;
}

export const ProcessHistory: React.FC<ProcessHistoryProps> = ({
  tasks,
  onClearHistory,
  onExportHistory,
  className = '',
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState<TaskType | 'all'>('all');
  const [filterStatus, setFilterStatus] = useState<'all' | 'completed' | 'failed'>('all');
  const [dateRange, setDateRange] = useState<'all' | 'today' | 'week' | 'month'>('all');

  // 过滤和搜索历史记录
  const filteredTasks = useMemo(() => {
    return tasks.filter(task => {
      // 搜索条件
      const matchesSearch =
        searchTerm === '' ||
        task.inputFiles[0].name.toLowerCase().includes(searchTerm.toLowerCase());

      // 任务类型过滤
      const matchesType = filterType === 'all' || task.type === filterType;

      // 状态过滤
      const matchesStatus =
        filterStatus === 'all' ||
        (filterStatus === 'completed' && task.status === 'completed') ||
        (filterStatus === 'failed' && task.status === 'failed');

      // 日期范围过滤
      const matchesDateRange =
        dateRange === 'all' ||
        {
          today: () => {
            const today = new Date();
            return task.createdAt.toDateString() === today.toDateString();
          },
          week: () => {
            const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
            return task.createdAt >= weekAgo;
          },
          month: () => {
            const monthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
            return task.createdAt >= monthAgo;
          },
        }[dateRange]();

      return matchesSearch && matchesType && matchesStatus && matchesDateRange;
    });
  }, [tasks, searchTerm, filterType, filterStatus, dateRange]);

  // 统计信息
  const stats = useMemo(() => {
    const completedTasks = tasks.filter(t => t.status === 'completed').length;
    const failedTasks = tasks.filter(t => t.status === 'failed').length;
    const totalTime = tasks.reduce((sum, task) => {
      if (task.completedAt && task.startedAt) {
        return sum + (task.completedAt.getTime() - task.startedAt.getTime()) / 1000;
      }
      return sum;
    }, 0);

    const spaceSaved = tasks.reduce((sum, task) => {
      if (task.status === 'completed' && task.result) {
        return sum + (task.result.originalSize - task.result.newSize);
      }
      return sum;
    }, 0);

    return {
      totalTasks: tasks.length,
      completedTasks,
      failedTasks,
      successRate: tasks.length > 0 ? (completedTasks / tasks.length) * 100 : 0,
      totalTime,
      spaceSaved,
    };
  }, [tasks]);

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';

    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 格式化时间
  const formatTime = (seconds: number): string => {
    if (seconds < 60) {
      return `${Math.round(seconds)}秒`;
    } else if (seconds < 3600) {
      return `${Math.floor(seconds / 60)}分${Math.round(seconds % 60)}秒`;
    } else {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      return `${hours}时${minutes}分`;
    }
  };

  // 格式化日期
  const formatDate = (date: Date): string => {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 获取任务类型标签
  const getTaskTypeLabel = (type: TaskType): string => {
    const labels: Record<TaskType, string> = {
      convert: '格式转换',
      compress: '视频压缩',
      resize: '分辨率调整',
      extract_audio: '提取音频',
      extract_frames: '提取帧',
      merge: '视频合并',
      split: '视频分割',
      rotate: '旋转视频',
      crop: '裁剪视频',
      add_watermark: '添加水印',
      stabilize: '稳定视频',
      denoise: '降噪',
      batch_process: '批量处理',
    };
    return labels[type] || type;
  };

  return (
    <div className={`space-y-6 ${className}`}>
      {/* 标题和操作按钮 */}
      <div className='flex items-center justify-between'>
        <div>
          <h2 className='text-2xl font-bold text-gray-900'>处理历史记录</h2>
          <p className='text-gray-600 mt-1'>
            共 {stats.totalTasks} 个任务 • 成功率 {stats.successRate.toFixed(1)}%
          </p>
        </div>

        <div className='flex items-center space-x-3'>
          <button
            onClick={onExportHistory}
            className='btn btn-outline flex items-center space-x-2'
            disabled={tasks.length === 0}
          >
            <Download className='w-4 h-4' />
            <span>导出记录</span>
          </button>

          <button
            onClick={onClearHistory}
            className='btn btn-danger flex items-center space-x-2'
            disabled={tasks.length === 0}
          >
            <Trash2 className='w-4 h-4' />
            <span>清空历史</span>
          </button>
        </div>
      </div>

      {/* 统计信息 */}
      <div className='grid grid-cols-2 md:grid-cols-4 gap-4'>
        <div className='card p-4 text-center'>
          <div className='text-2xl font-bold text-blue-600'>{stats.totalTasks}</div>
          <div className='text-sm text-gray-600'>总任务数</div>
        </div>

        <div className='card p-4 text-center'>
          <div className='text-2xl font-bold text-green-600'>{stats.completedTasks}</div>
          <div className='text-sm text-gray-600'>成功任务</div>
        </div>

        <div className='card p-4 text-center'>
          <div className='text-2xl font-bold text-red-600'>{stats.failedTasks}</div>
          <div className='text-sm text-gray-600'>失败任务</div>
        </div>

        <div className='card p-4 text-center'>
          <div className='text-2xl font-bold text-purple-600'>
            {formatFileSize(stats.spaceSaved)}
          </div>
          <div className='text-sm text-gray-600'>节省空间</div>
        </div>
      </div>

      {/* 搜索和过滤 */}
      <div className='card p-4'>
        <div className='grid grid-cols-1 md:grid-cols-4 gap-4'>
          {/* 搜索 */}
          <div className='relative'>
            <Search className='w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400' />
            <input
              type='text'
              placeholder='搜索文件名...'
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className='w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500'
            />
          </div>

          {/* 任务类型过滤 */}
          <div>
            <select
              value={filterType}
              onChange={e => setFilterType(e.target.value as TaskType | 'all')}
              className='w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500'
            >
              <option value='all'>所有类型</option>
              <option value='convert'>格式转换</option>
              <option value='compress'>视频压缩</option>
              <option value='extract_audio'>提取音频</option>
              <option value='batch_process'>批量处理</option>
            </select>
          </div>

          {/* 状态过滤 */}
          <div>
            <select
              value={filterStatus}
              onChange={e => setFilterStatus(e.target.value as 'all' | 'completed' | 'failed')}
              className='w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500'
            >
              <option value='all'>所有状态</option>
              <option value='completed'>已完成</option>
              <option value='failed'>已失败</option>
            </select>
          </div>

          {/* 日期范围 */}
          <div>
            <select
              value={dateRange}
              onChange={e => setDateRange(e.target.value as 'all' | 'today' | 'week' | 'month')}
              className='w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500'
            >
              <option value='all'>所有时间</option>
              <option value='today'>今天</option>
              <option value='week'>最近一周</option>
              <option value='month'>最近一月</option>
            </select>
          </div>
        </div>
      </div>

      {/* 历史记录列表 */}
      <div className='card p-4'>
        <div className='space-y-3 max-h-96 overflow-y-auto'>
          {filteredTasks.length === 0 ? (
            <div className='text-center py-8'>
              <File className='w-12 h-12 text-gray-400 mx-auto mb-4' />
              <p className='text-gray-600'>没有找到匹配的历史记录</p>
            </div>
          ) : (
            filteredTasks.map(task => (
              <div
                key={task.id}
                className='p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors'
              >
                <div className='flex items-start justify-between'>
                  <div className='flex items-start space-x-3 flex-1'>
                    {/* 状态图标 */}
                    {task.status === 'completed' ? (
                      <CheckCircle className='w-6 h-6 text-green-500 mt-1' />
                    ) : (
                      <XCircle className='w-6 h-6 text-red-500 mt-1' />
                    )}

                    <div className='flex-1 min-w-0'>
                      <div className='flex items-center space-x-2 mb-2'>
                        <span className='font-medium text-gray-900 truncate'>
                          {task.inputFiles[0].name}
                        </span>

                        <span
                          className={`px-2 py-1 text-xs rounded-full ${
                            task.status === 'completed'
                              ? 'bg-green-100 text-green-800'
                              : 'bg-red-100 text-red-800'
                          }`}
                        >
                          {task.status === 'completed' ? '成功' : '失败'}
                        </span>

                        <span className='px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded'>
                          {getTaskTypeLabel(task.type)}
                        </span>
                      </div>

                      <div className='grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-gray-600'>
                        <div className='flex items-center space-x-1'>
                          <Calendar className='w-4 h-4' />
                          <span>{formatDate(task.createdAt)}</span>
                        </div>

                        <div className='flex items-center space-x-1'>
                          <Clock className='w-4 h-4' />
                          <span>
                            {task.startedAt && task.completedAt
                              ? formatTime(
                                  (task.completedAt.getTime() - task.startedAt.getTime()) / 1000
                                )
                              : 'N/A'}
                          </span>
                        </div>

                        {task.result && (
                          <div className='flex items-center space-x-1'>
                            <span>
                              节省空间:{' '}
                              {formatFileSize(task.result.originalSize - task.result.newSize)}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  <div className='flex items-center space-x-2'>
                    {task.result && task.result.outputFiles.length > 0 && (
                      <button
                        onClick={() => {
                          // 打开输出文件
                          console.log('打开文件:', task.result?.outputFiles[0]);
                        }}
                        className='btn btn-outline btn-sm'
                      >
                        打开文件
                      </button>
                    )}
                  </div>
                </div>

                {/* 错误信息（如果有） */}
                {task.error && (
                  <div className='mt-2 p-2 bg-red-50 border border-red-200 rounded text-sm text-red-700'>
                    <span className='font-medium'>错误:</span> {task.error.message}
                  </div>
                )}
              </div>
            ))
          )}
        </div>

        {/* 分页信息 */}
        {filteredTasks.length > 0 && (
          <div className='flex items-center justify-between mt-4 pt-4 border-t border-gray-200'>
            <span className='text-sm text-gray-600'>显示 {filteredTasks.length} 条记录</span>

            <div className='flex items-center space-x-2'>
              <button className='btn btn-outline btn-sm'>上一页</button>
              <button className='btn btn-outline btn-sm'>下一页</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ProcessHistory;
